﻿using My.Admin.Service;
using My.Core.DynamicProxy;
using My.Core.Extensions;
using My.Core.Quartz.Model;
using My.Core.Quartz.Server.IServer;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace My.Core.Quartz.Server
{
    public class SysTasksQzService : BaseService<SysTasks>, ISysTasksQzService, ITransientAutoInject
    {
        /// <summary>
        /// 添加任务
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        public int AddTasks(SysTasks parm)
        {
            parm.IsStart = false;

            SetAssembleName(parm);

            return Add(parm);
        }

        private void SetAssembleName(SysTasks parm)
        {
            if (parm.ApiUrl.IsNotEmpty() && parm.TaskType == 2)
            {
                parm.AssemblyName = "Tasks";
                parm.ClassName = "TaskScheduler.Job_HttpRequest";
            }

            if (!parm.SqlText.IsNotEmpty() && parm.TaskType == 3)
            {
                parm.AssemblyName = "Tasks";
                parm.ClassName = "TaskScheduler.Job_SqlExecute";
            }
        }

        /// <summary>
        /// 更新任务
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        public int UpdateTasks(SysTasks parm)
        {
            SetAssembleName(parm);

            return Update(f => f.ID == parm.ID, f => new SysTasks
            {
                ID = parm.ID,
                Name = parm.Name,
                JobGroup = parm.JobGroup,
                Cron = parm.Cron,
                AssemblyName = parm.AssemblyName,
                ClassName = parm.ClassName,
                Remark = parm.Remark,
                TriggerType = parm.TriggerType,
                IntervalSecond = parm.IntervalSecond,
                JobParams = parm.JobParams,
                Update_time = DateTime.Now,
                BeginTime = parm.BeginTime,
                EndTime = parm.EndTime,
                TaskType = parm.TaskType,
                ApiUrl = parm.ApiUrl,
                SqlText = parm.SqlText,
                RequestMethod = parm.RequestMethod,
            });
        }
    }
}
